﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Coslen.Framework.Logging;
using Coslen.Framework.Logging.Log4Net;
using Coslen.Framework.Logging.NLog;
using Coslen.Framework.Logging.Services;
using Coslen.Framework.Logging.Services.Interfaces;

namespace Coslen.TahorCRM.UI.www.Areas.Admin.Controllers
{
    public class LoggingController : Controller
    {
        public ILoggingService LoggingService { get; set; }

        public LoggingController()
            :this(new LoggingService())
        {
            
        }

        public LoggingController(ILoggingService loggingService)
        {
            this.LoggingService = loggingService;
        }

        //
        // GET: /Admin/Logging/
        public ActionResult Index(string Period, string LoggerProviderName, string LogLevel, int? page, int? PageSize)
        {            
            // Set up our default values
            string defaultPeriod = Session["Period"] == null ? "Today" : Session["Period"].ToString();
            string defaultLogType = Session["LoggerProviderName"] == null ? "All" : Session["LoggerProviderName"].ToString();
            string defaultLogLevel = Session["LogLevel"] == null ? "Error" : Session["LogLevel"].ToString();

            // Determine if the parameters have values
            Period = string.IsNullOrWhiteSpace(Period) ? defaultPeriod : Period;
            LoggerProviderName = string.IsNullOrWhiteSpace(LoggerProviderName) ? defaultLogType : LoggerProviderName;
            LogLevel = string.IsNullOrWhiteSpace(LogLevel) ? defaultLogLevel : LogLevel;

            // Get the model from the service
            var model = LoggingService.GetLoggingIndexModel(Period, LoggerProviderName, LogLevel, page, PageSize);
           
            // Put this into the ViewModel so our Pager can get at these values
            ViewBag.Period = model.Period;
            ViewBag.LoggerProviderName = model.LoggerProviderName;
            ViewBag.LogLevel = model.LogLevel;
            ViewBag.PageSize = model.PageSize;

            // Put the info into the Session so that when we browse away from the page and come back that the last settings are rememberd and used.
            Session["Period"] = model.Period;
            Session["LoggerProviderName"] = model.LoggerProviderName;
            Session["LogLevel"] = model.LogLevel;

            return View(model);
        }

        //
        // GET: /Logging/Details/5
        public ActionResult Details(string loggerProviderName, string id)
        {
            var model = LoggingService.GetById(loggerProviderName, id);

            return View(model);
        }

        //
        // GET: /Logging/Manage
        public ActionResult Manage()
        {
            LoggingManageModel model = LoggingService.GetNewLoggingManageModel();

            return View(model);
        }

        //
        // POST: /Logging/Manage/
        [HttpPost]
        public ActionResult Manage(LoggingManageModel model)
        {
            try
            {
                string[] logLevels = new string[] { "Warn" };
                LoggingService.ClearLog(model.LogSourceName, model.StartDate, model.EndDate, logLevels);

                ViewBag.Message = "The log has been cleared";

                LoggingService.PopulateListForLoggingManageModel(model);

                return View(model);
            }
            catch
            {
                LoggingService.PopulateListForLoggingManageModel(model);
                return View();
            }
        }


        #region Logging Trigger Event

        //[Authorize(Users = "CoslenAdmin")]
        public ActionResult ApplicationErrorTest()
        {
            return View();
        }

        //[Authorize(Users = "CoslenAdmin")]
        public ActionResult ServerSide404(int id)
        {
            this.HttpContext.AddError(new HttpException(404, "Invalid Id - " + id));
            return View();
        }

        //[Authorize(Users = "CoslenAdmin")]
        public ActionResult ApplicationException()
        {
            // Throw a test error so that we can see that it is handled by Elmah
            // To test go to the ~/elmah.axd page to see if the error is being logged correctly
            throw new ApplicationException("Testing Application Exception Handling Page");
        }

        //[Authorize(Users = "CoslenAdmin")]
        public ActionResult NLogTest()
        {
            NLogLogger logger = new NLogLogger();
            logger.Info("We're on the Index page for Activities - NLog");

            try
            {
                throw new Exception("A test exception");
            }
            catch (Exception ex)
            {
                logger.Error("An error has occurred", ex);
            }

            return View();
        }

        //[Authorize(Users = "CoslenAdmin")]
        public ActionResult Log4NetTest()
        {
            Log4NetLogger logger = new Log4NetLogger();
            logger.Info("We're on the Index page for Activities - Log4Net");

            try
            {
                throw new Exception("A test exception");
            }
            catch (Exception ex)
            {
                logger.Error("An error has occurred", ex);
            }

            return View();
        }

        #endregion
    }
}
